// ==UserScript==
// @name         淘宝自动上架
// @version      0.1
// @description  淘宝自动上架
// @author       Rainbow
// @match        *://*.taobao.com/*
// @run-at       document-idle
// @grant GM_setValue
// @grant GM_getValue
// @grant unsafeWindow
// @grant window.close
// @grant window.focus
// @require https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js
// ==/UserScript==

(function () {
    console.log('Rainbow Script for TaoBao')
    window.confirm = function () { return true }
    var timeGap = 20; //初始运行间隔，单位：秒
    var nextPageTimeGap = 2; //翻页间隔，单位：分钟
    var nodeCount = 3; //每次打开页面数量
    var rootPageSelector = "tbody.ant-table-tbody > tr:nth-child(n+1) > td> div > a:nth-child(2)";
    var catalogSelector = "#struct-categoryHistory > div > div > div.next-tabs-bar > div > div > div > div > div:nth-child(1) > div";
    var routerNextSelector = "#struct-submit > button"
    var uploadSelector = "#struct-startTime > div > div.next-col.next-col-20.sell-o-addon-content > div.sell-o-addon-info > div.info-content > div > span > span:nth-child(1) > label > label > span > input[type=radio]";
    var uploadSubmitSelector = "#button-submit";
    var bookNameSelector = "#struct-p-2043183 > div.sell-catProp-struct > div.content > span > input[type=text]";
    var publishNameSelector = "#struct-p-122216620 > div.sell-catProp-struct > div.content > span > div > div > input";
    var authorNameSelector = "#struct-p-2043189 > div.sell-catProp-struct > div.content > span > input[type=text]";
    var nextPageSelector = "#h-app-right-content > div > div.offline-list-container > div.ant-table-wrapper.offline-list-table.m-t-md > div > div > ul > li.ant-pagination-next > a";
    var catalogDescSelector = "#text-catpath";
    var selectorResult = document.querySelector(rootPageSelector);
    var statusMap = new Map();
    var runningCount = 0;
    var itemStr = "https://item.publish.taobao.com/sell/publish.htm/?itemId=";
    if (null != selectorResult) {
        selectorResult.forEach(element => {
            console.log(element)
        });
    }
    if (window.location.href.startsWith("https://item.publish.taobao.com/sell/publish.htm")) {
        console.log(GetQueryString("itemId"))
        setTimeout(() => {
            console.log('erase confirm publish edit')
            let btn = document.getElementById('button-catpath');
            window.confirm = function () { return true }
            btn.click()

        }, 5 * 1000);
    }
    if (window.location.href.startsWith("https://item.upload.taobao.com/router/publish.htm")) {
        console.log(GetQueryString("itemId"))
        setTimeout(() => {
            console.log('erase confirm publish router')
            let cataBtn = document.querySelector(catalogSelector);
            let nextBtn = document.querySelector(routerNextSelector);
            window.confirm = function () { return true }
            cataBtn.click()
            nextBtn.click()
        }, 5 * 1000);
    }
    if (window.location.href.startsWith("https://item.upload.taobao.com/sell/publish.htm")) {
        console.log(GetQueryString("itemId"))
        setTimeout(() => {
            try {
                console.log('erase confirm publish upload')
                //检测是否需要更改目录
                let catalogDescNode = document.querySelector(catalogDescSelector);
                let catalogDesc = catalogDescNode.innerHTML;
                if(catalogDesc.indexOf('其他') > -1 && catalogDesc.indexOf('漫画') < 0)
                {
                    let catbtn = document.getElementById('button-catpath');
                    window.confirm = function () { return true }
                    catbtn.click()
                }else{
                    let uploadBtn = document.querySelector(uploadSelector);
                    let nextBtn = document.querySelector(uploadSubmitSelector);
                    let bookNameNode = document.querySelector(bookNameSelector);
                    try {
                        if (bookNameNode.value == undefined || bookNameNode.value == null || bookNameNode.value.trim() == "") {
                            $(bookNameNode).val("1")
                            bookNameNode.dispatchEvent(new Event('input'));
                        }
                        let publishNameNode = document.querySelector(publishNameSelector);
                        if (publishNameNode.value == undefined || publishNameNode.value == null || publishNameNode.value.trim() == "") {
                            $(publishNameNode).val("1")
                            publishNameNode.dispatchEvent(new Event('input'));
                        }
                        let authorNameNode = document.querySelector(authorNameSelector);
                        if (authorNameNode.value == undefined || authorNameNode.value == null || authorNameNode.value.trim() == "") {
                            $(authorNameNode).val("1")
                            authorNameNode.dispatchEvent(new Event('input'));
                        }
                    } catch (error) {

                    }
                    window.confirm = function () { return true }
                    uploadBtn.click()
                    nextBtn.click()
                    setTimeout(() => {
                        GM_setValue(itemStr + GetQueryString("itemId"), "fail")
                        window.close()
                    }, 90 * 1000);
                }
            } catch (error) {

            }

        }, 5 * 1000);
    }
    if (window.location.href.startsWith("https://item.taobao.com/item.htm")) {
        window.close()
    }
    setTimeout(() => {
        startup()
    }, timeGap * 1000);
    function startup() {
        if (window.location.href.startsWith("https://healthcenter.taobao.com/")) {
            console.log('start up')
            var selectorResult = document.querySelectorAll(rootPageSelector);
            var nextPageNode = document.querySelector(nextPageSelector)
            if (null != selectorResult) {
                // selectorResult.forEach(element => {
                //     console.log(element)
                //     statusMap.set(element.getAttribute("href"), 'start')
                //     element.click()
                //     //临时注释
                //     //throw new Error('end')
                // });
                for (let index = 0; index < selectorResult.length; index++) {
                    if(index != 0 && index % nodeCount == 0)
                    {
                        //休眠
                        console.log('sleep')
                        sleep2(90*1000)
                    }
                    const element = selectorResult[index];
                    console.log(element)
                    statusMap.set(element.getAttribute("href"), 'start')
                    element.click()
                    
                }
                nextPageNode.click()
                setInterval(() => {
                    runningCount++;
                    console.log('loop run,runningcount:'+runningCount)

                    if (runningCount >= 620) {
                        window.location.reload()
                    }
                    let tempResult = document.querySelectorAll(rootPageSelector);
                    console.log(tempResult)
                    if (null != tempResult) {
                        tempResult.forEach(element => {
                            console.log(element)
                            let url = element.getAttribute("href");
                            if (GM_getValue(url) == "fail") {
                                //continue;
                            } else {
                                element.click()
                            }
                        });
                    }
                    nextPageNode.click()
                }, 2 * 60 * 1000);
            }
        }

    }

    function sleep(time) {
        return new Promise(resolve => {
                setTimeout(resolve, time)
            }
        )
    }

    //参数n为休眠时间，单位为毫秒:
    function sleep2(n) {
        var start = new Date().getTime();
        //  console.log('休眠前：' + start);
        while (true) {
            if (new Date().getTime() - start > n) {
                break;
            }
        }
        // console.log('休眠后：' + new Date().getTime());
    }
    

    function GetQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);  //获取url中"?"符后的字符串并正则匹配
        var context = "";
        if (r != null)
            context = r[2];
        reg = null;
        r = null;
        return context == null || context == "" || context == "undefined" ? "" : context;
    }
})();